package com.uha.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.*;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author uha
 * @date 2023/6/15
 * @apiNote
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ReggieResult<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        if (ex.getMessage().contains("Duplicate entry")){
            String[] s = ex.getMessage().split(" ");
            String msg ="账号："+ s[2] + "   已存在~";
            return ReggieResult.error(msg);
        }


        return ReggieResult.error("未知错误~");
    }


    /**
     * 捕获自己的异常
     * @param ex ex
     * @return ReggieResult
     */
    @ExceptionHandler(CustomException.class)
    public ReggieResult<String> exceptionHandler(CustomException ex){

        return ReggieResult.error(ex.getMessage());
    }

}
